package hxy.bytecode.lock;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by haicheng.lhc on 17/05/2017.
 *
 * @author haicheng.lhc
 * @date 2017/05/17
 */
public class ReentrantLockTest extends Thread {

    public static ReentrantLock lock = new ReentrantLock();
    public static int i = 0;

    public ReentrantLockTest(String name) {
        super.setName(name);
    }

    @Override
    public void run() {
        ArrayList<Integer> a = new ArrayList();
//        10000000
        for (int j = 0; j < 100000; j++) {
            a.add(j);
            lock.lock();
            try {
//                这就是可重入，对于同一把锁是可以获取两次的。 https://www.jianshu.com/p/155260c8af6c 有啥意义
                lock.lock();
                try {
                    System.out.println(this.getName() + " " + i);
                    i++;
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }
        }
    }

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        ReentrantLockTest test1 = new ReentrantLockTest("thread1");
        ReentrantLockTest test2 = new ReentrantLockTest("thread2");

        test1.start();
        test2.start();
        test1.join();
        test2.join();
        System.out.println("finally value:" + i);
        long end = System.currentTimeMillis();

        long total = end - start;
        System.out.println("total time:" + total);


    }
}
